<template>
  <div class="sidebar">
    <div style="position: relative; background: #fff; width: 266px; left: 12px">
      <div class="logo" @click="gohome">
        <img src="/logo.png" alt="CHN ENERGY" />
      </div>
      <div class="menu-items">
        <!-- <router-link to="/qa" class="menu-item active" active-class="active"> -->
        <div class="menu-item active" @click="goqa">
          <div>
            <img src="/src/assets/1.png" alt="" />
            <span style="font-weight: 700">开启新对话</span>
          </div>
        </div>
        <!-- <div class="menu-item active" @click="goqa">
        <div>
          <img src="/src/assets/1.png" alt="" />
          <span style="font-weight: 700">PPT助手</span>
        </div>
      </div> -->
        <!-- </router-link> -->
        <!-- <router-link to="/history" class="menu-item" active-class="active1">
        <div>
          <img :src="$route.path == '/history' ? '/src/assets/2-1.png' : '/src/assets/2.png'" alt="" />
          <span>历史对话</span>
        </div>
      </router-link> -->
        <router-link to="/favorite" class="menu-item" active-class="active1">
          <div>
            <img
              :src="
                $route.path == '/favorite' ? '/src/assets/3-1.png' : '/src/assets/3.png'
              "
              alt=""
            />
            <span>我的收藏</span>
          </div>
        </router-link>

        <router-link
          to="/knowledgeBase"
          class="menu-item"
          active-class="active1"
          v-if="isAdmin"
        >
          <div>
            <span>知识库</span>
          </div>
        </router-link>
      </div>
    </div>
    <div class="history-content">
      <!-- <div v-for="(group, date) in groupedHistory" :key="date" class="history-group" :style="{display:$route.path == '/history'?'block':$route.path == '/qa'?'block':'none'}"> -->
      <div v-for="(group, date) in groupedHistory" :key="date" class="history-group">
        <div class="flex">
          <div class="date-header">{{ date }}</div>
          <div class="more" @click="gohistory">全部对话</div>
        </div>
        <div
          v-for="item in group"
          :key="item.id"
          class="history-item"
          @click="handleHistoryClick(item)"
          :style="{
            background: item.id == historyId ? '#e8e8e8' : '',
            borderRadius: item.id == historyId ? '10px' : '',
          }"
        >
          <div class="item-content">
            <div class="item-text">{{ item.name }}</div>
            <!-- <div class="item-create_time">{{ item.create_time }}</div> -->
          </div>
          <!-- <div class="item-actions">
            <div class="item-create_time">{{ item.content }}</div>
          </div> -->
        </div>
      </div>
    </div>

    <el-dropdown placement="top" @command="handleCommand" trigger="click">
      <div class="user-info menu-item" v-if="username">
        <div>
          <img src="/src/assets/userimg.png" alt="" />
          <span>{{ username }}</span>
        </div>
      </div>
      <template #dropdown>
        <el-dropdown-menu style="width: 162px; padding: 10px">
          <!-- <el-dropdown-item>
            <img src="../assets/14.png" alt="" /> 系统设置</el-dropdown-item>
          <el-dropdown-item>
            <img src="../assets/15.png" alt="" /> 联系我们</el-dropdown-item> -->
          <el-dropdown-item command="退出登录">
            <img src="../assets/16.png" alt="" /> 退出登录
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>

    <div class="user-info menu-item" @click="gologin" v-if="!username">
      <div>
        <span>未登录</span>
      </div>
    </div>
    <!-- <div class="user-info menu-item">
      <div>
        <img src="/src/assets/userimg.png" alt="" />
        <span>用户名称</span>
      </div>
    </div> -->
    <el-dialog v-model="dialogVisible" width="600">
      <img src="../assets/13.png" alt="" style="margin: auto" />
      <div class="dialogtitle">确认退出登录</div>
      <div class="title1">您确定，要退出当前账号吗？</div>
      <template #footer>
        <div class="footer">
          <div class="cancal" @click="dialogVisible = false">取消</div>
          <div class="outok" @click="loginout">确认退出</div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  computed,
  defineComponent,
  nextTick,
  onBeforeMount,
  reactive,
  toRefs,
  watchEffect,
  watch,
  onMounted,
} from "vue";
import { useRouter, useRoute } from "vue-router";
import { Loginout } from "../api/login";
import { getSessionsListbydate } from "../api/home";
import { ElMessage } from "element-plus";

export default defineComponent({
  name: "Sidebar",
  setup() {
    const router = useRouter();
    const route = useRoute();
    const state = reactive({
      tabindex: 0,
      dialogVisible: false,
      username: localStorage.getItem("username"),
      historyData: [],
      queryForm: {
        page: 1,
        count: 20,
      },
      searchQuery: "",
      historyId: "",
      isAdmin: localStorage.getItem("isAdmin"),
    });

    const handleMenuClick = (e) => {
      state.tabindex = e;
    };

    const handleCommand = (command) => {
      if (command == "退出登录") {
        state.dialogVisible = true;
      }
    };

    const gologin = () => {
      router.push({
        name: "login",
      });
    };

    const gohistory = () => {
      router.push({
        name: "history",
        query: {
          isid: "",
        },
      });
    };

    const gohome = () => {
      router.push({
        name: "home",
      });
    };

    const loginout = async () => {
      const res = await Loginout();
      if (res.code == 0) {
        ElMessage.success("退出成功，请重新登陆");
        localStorage.removeItem("token");
        localStorage.removeItem("username");
        setTimeout(() => {
          router.push({
            name: "login",
          });
        }, 1000);
      } else {
        ElMessage.error(res.msg);
      }
    };

    const goqa = () => {
      router.push({
        name: "questionAnswer",
      });
    };

    // 按日期分组的计算属性
    const groupedHistory = computed(() => {
      const now = new Date(); //今天
      const now1 = new Date(); // 昨天
      const now2 = new Date(); // 七天内
      const now3 = new Date(); // 三十天内
      now1.setDate(now1.getDate() - 1);
      now2.setDate(now2.getDate() - 7);
      now3.setDate(now3.getDate() - 30);
      // 今天
      const year = now.getFullYear();
      const month = String(now.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
      const day = String(now.getDate()).padStart(2, "0"); // 日期需要两位数表示
      const today = year + "-" + month + "-" + day;
      // 昨天
      const year1 = now1.getFullYear();
      const month1 = String(now1.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
      const day1 = String(now1.getDate()).padStart(2, "0"); // 日期需要两位数表示
      const yesterday = year1 + "-" + month1 + "-" + day1;
      // 七天内
      const year2 = now2.getFullYear();
      const month2 = String(now2.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
      const day2 = String(now2.getDate()).padStart(2, "0"); // 日期需要两位数表示
      const sevendays = year2 + "-" + month2 + "-" + day2;
      // 三十天内
      const year3 = now3.getFullYear();
      const month3 = String(now3.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
      const day3 = String(now3.getDate()).padStart(2, "0"); // 日期需要两位数表示
      const thirtydays = year3 + "-" + month3 + "-" + day3;

      const filtered = state.historyData.filter((item) =>
        item.name.toLowerCase().includes(state.searchQuery.toLowerCase())
      );
      return filtered.reduce((groups, item) => {
        if (item.date == today || item.date == "今天") {
          item.date = "今天";
        } else if (item.date == yesterday || item.date == "昨天") {
          item.date = "昨天";
        } else if (
          new Date(Date.parse(item.date)) > new Date(Date.parse(sevendays)) ||
          item.date == "七天内"
        ) {
          item.date = "七天内";
        } else if (
          new Date(Date.parse(item.date)) > new Date(Date.parse(thirtydays)) ||
          item.date == "三十天内"
        ) {
          item.date = "三十天内";
        } else {
          item.date = item.date.slice(0, 7);
        }
        if (!groups[item.date]) {
          groups[item.date] = [];
        }
        groups[item.date].push(item);
        return groups;
      }, {});
    });

    // 处理历史记录点击
    const handleHistoryClick = (item) => {
      // console.log(item)
      state.historyId = item.id;
      // 导航到对话页面并传递对话内容
      router.push({
        name: "chat",
        query: {
          id: item.id,
        },
        // params: { },
        // state: { content: item.content },
      });
    };

    // 获取会话列表
    const getphrasesList = async () => {
      const now3 = new Date(); // 三十天内
      now3.setDate(now3.getDate() - 30);
      const year3 = now3.getFullYear();
      const month3 = String(now3.getMonth() + 1).padStart(2, "0"); // 月份是从0开始的，所以要加1，并且需要两位数表示
      const day3 = String(now3.getDate()).padStart(2, "0"); // 日期需要两位数表示
      const thirtydays = year3 + "-" + month3 + "-" + day3;
      const res = await getSessionsListbydate(thirtydays);
      if (res.code == 0) {
        res.data.items.forEach((item) => {
          item.date = item.create_time.split("T")[0];
          item.create_time = item.create_time.split(".")[0].replace("T", " ");
        });
        state.historyData = res.data.items;
      } else {
        state.historyData = [];
      }
    };

    watch(
      () => router.currentRoute.value.query.isid,
      () => {
        getphrasesList();
      }
    );

    watch(
      () => router.currentRoute.value.query.question,
      () => {
        getphrasesList();
      }
    );

    watch(
      () => router.currentRoute.value.name,
      () => {
        getphrasesList();
      }
    );

    watch(
      () => router.currentRoute.value.query.id,
      () => {
        state.historyId = router.currentRoute.value.query.id;
      }
    );

    onMounted(() => {
      // state.isAdmin = localStorage.getItem('isAdmin')
      // console.log(state.isAdmin)
      getphrasesList();
    });

    return {
      ...toRefs(state),
      handleMenuClick,
      handleCommand,
      gologin,
      loginout,
      gohome,
      goqa,
      groupedHistory,
      handleHistoryClick,
      getphrasesList,
      gohistory,
    };
  },
});
</script>

<style scoped>
.sidebar {
  width: 290px;
  height: 100vh;
  background-color: #fff;
  display: flex;
  flex-direction: column;
  padding-bottom: 20px;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
}

.flex {
  display: flex;
  justify-content: space-between;
}

.more {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 400;
  font-size: 12px;
  color: #5773fe;
  line-height: 18px;
  text-align: right;
  font-style: normal;
  text-transform: none;
  cursor: pointer;
}

:deep().el-dropdown-menu {
  width: 162px !important;
  text-align: left;
}

:deep().el-dropdown-menu__item {
  padding-left: 10px !important;
  padding-right: 10px !important;
  line-height: 42px;
}

:deep().el-dialog__body {
  padding-top: 10px !important;
}

:deep().el-dialog {
  border-radius: 24px;
  padding-bottom: 40px !important;
}

.footer {
  display: flex;
  margin-top: 30px;
}

.el-dropdown-menu img {
  width: 24px;
  height: 24px;
  margin-right: 4px;
}

.footer div {
  cursor: pointer;
}

.cancal {
  line-height: 54px;
  height: 54px;
  border-radius: 27px;
  width: 170px;
  background: #f3f4f6;
  text-align: center;
  color: #666666;
  margin-left: 78px;
  margin-right: 32px;
}

.outok {
  line-height: 54px;
  height: 54px;
  border-radius: 27px;
  width: 240px;
  text-align: center;
  background: #6966db;
  color: #ffffff;
}

.dialogtitle {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 24px;
  color: #3d3d3d;
  line-height: 34px;
  text-align: center;
  font-style: normal;
  text-transform: none;
  margin-top: 32px;
}

:deep().el-dialog__footer {
  padding: 0;
  padding-top: 20px;
}

/* :deep().el-button :hover{
    background: transparent !important;
} */

.title1 {
  margin-top: 24px;
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 400;
  font-size: 24px;
  color: #333333;
  line-height: 34px;
  text-align: center;
  font-style: normal;
  text-transform: none;
}

:deep().el-dialog__headerbtn {
  display: none !important;
}

.logo {
  margin: auto;
  margin-top: 44px;
  margin-bottom: 32px;
  cursor: pointer;
}

.logo img {
  max-width: 184px;
  height: auto;
  margin: auto;
}

.menu-items {
  /* flex: 1; */
  overflow-y: auto;
}

.menu-item {
  display: flex;
  width: 242px;
  margin: auto;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 24px;
  opacity: 1;
  background: #f5f9ff;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 700;
  height: 48px;
  line-height: 48px;
}

.menu-item div {
  margin: auto;
  display: flex;
  align-items: center;
}

.menu-item img {
  width: auto;
  height: 24px;
  margin-right: 10px;
}

.menu-item span {
  width: 70px;
  text-align: left;
}

/* .menu-item:hover {
  background-color: #f5f5f5;
} */

.active div {
  margin: auto;
  display: flex;
  align-items: center;
}

.menu-item span {
  font-size: 14px;
  color: #333;
  font-weight: 400;
}

.active {
  height: 48px;
  line-height: 48px;
  display: flex;
  width: 242px;
  margin: auto;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 24px;
  opacity: 1;
  background: #f5f9ff;
  margin-bottom: 20px;
  font-size: 18px;
  font-weight: 700 !important;
  background-color: #ddebff;
}

.active1 {
  height: 48px;
  line-height: 48px;
  display: flex;
  width: 242px;
  margin: auto;
  align-items: center;
  cursor: pointer;
  transition: all 0.3s ease;
  border-radius: 24px;
  opacity: 1;
  margin-bottom: 34px;
  font-size: 18px;
  font-weight: 700;
  background-color: #5450cc;
  color: #fff !important;
}

.history-group {
  margin-bottom: 10px;
}

.date-header {
  margin-bottom: 8px;
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 14px;
  color: #333333;
  line-height: 18px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.history-item {
  /* display: flex;
  justify-content: space-between; */
  align-items: center;
  padding: 13px 10px;
  background: white;
  /* border: 1px solid #8CDCDC; */
  /* border-radius: 8px; */
  /* margin-bottom: 8px; */
  cursor: pointer;
  transition: all 0.3s ease;
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 700;
  font-size: 14px;
  color: #333333;
  line-height: 18px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.history-item:hover {
  /* transform: translateY(-2px); */
  /* box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); */
  background: #f1f7ff;
}

.item-content {
  flex: 1;
  display: flex;
  justify-content: space-between;
}

.item-text {
  font-family: Alibaba PuHuiTi 2, Alibaba PuHuiTi 20;
  font-weight: 400;
  font-size: 14px;
  color: #333333;
  line-height: 14px;
  text-align: left;
  font-style: normal;
  text-transform: none;
}

.history-content {
  width: 262px;
  margin-left: auto;
  line-height: 40px;
  flex: 2;
  overflow-y: scroll;
  /* scrollbar-width: none; */
  /* Firefox */
  /* -ms-overflow-style: none; */
  scrollbar-color: #dadada transparent;
  padding-right: 20px;
  box-sizing: border-box;
  margin-top: -337px;
  padding-top: 337px;
}

.item-create_time {
  font-size: 12px;
  color: #999;
  align-items: center;
  display: flex;
}

.active span {
  color: #5773fe;
}

.active1 span {
  color: #fff;
}

.menu-item :focus {
  outline: none !important;
}

.el-dropdown {
  outline: none !important;
}

/* .user-info {
  padding: 20px;
  border-top: 1px solid #eee;
  display: flex;
  align-items: center;
  background-color: #fafafa;
}

.user-info i {
  margin-right: 12px;
  font-size: 18px;
  color: #666;
}

.user-info span {
  font-size: 14px;
  color: #333;
} */

@media (max-width: 768px) {
  .sidebar {
    width: 250px;
  }

  .menu-item {
    padding: 15px 20px;
  }

  .menu-item i {
    font-size: 20px;
  }

  .user-info {
    padding: 15px 20px;
  }
}
</style>
